<template>
  <a-modal
    class="image-out-painting"
    v-model:visible="visible"
    title="AI-扩图"
    :footer="false"
    @cancel="closeModal"
  >
  <a-row gutter="16">
    <a-col span="12">
      <h4>原始图片</h4>
      <img :src="picture?.url" :alt="picture?.name" style="width: 100%"/>
    </a-col>
    <a-col span="12">
      <h4>扩图结果</h4>
      <img v-if="resultImageUrl" :src="resultImageUrl" :alt="picture?.name" style="width: 100%"/>
    </a-col>
  </a-row>
    <div style="margin-top: 16px"></div>
    <a-flex justify="center" gap="16">
      <a-button type="primary" :loading="!!taskId" ghost @click="createTask">生成图片</a-button>
      <a-button v-if="resultImageUrl" type="primary" :loading="uploadLoading" @click="handleUpload">应用结果</a-button>
    </a-flex>
  </a-modal>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { createPictureOutputTaskUsingPost, uploadPictureByUrlUsingPost, getPictureOutPaintingTaskUsingGet } from '@/api/pictureController.ts'
import { message } from 'ant-design-vue';

interface Props {
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()
const resultImageUrl = ref<string>('')

const visible = ref(false)

const openModal = () => {
  visible.value = true
}

const closeModal = () => {
  visible.value = false
}
// 暴露函数给父组件
defineExpose({
  openModal,
})

const uploadLoading = ref(false)

/**
 * 上传图片
 * @param file
 */
const handleUpload = async () => {
  uploadLoading.value = true;
  try {
    const params: API.PictureUploadRequest = {
      fileUrl : resultImageUrl.value,
      spaceId : props.spaceId
    }
    if (props.picture){
      params.id = props.picture.id;
    }
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.data.code === 0 && res.data.data) {
      message.success('上传成功');
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data.data);
      closeModal()
    } else {
      message.error('上传失败' + res.data.message);
    }
  }catch (e) {
    console.error('上传失败' + e);
    message.error('上传失败' + e.message);
  }
  uploadLoading.value = false;
}

// 任务id
let taskId = ref<string>()

/**
 * 创建扩图任务
 */
const createTask = async () => {
  if(!props.picture?.id) {
    return
  }
  const res = await createPictureOutputTaskUsingPost({
    pictureId: props.picture.id,
    // 根据需要设置扩图参数
    parameters: {
      xScale: 2,
      yScale: 2,
    }
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('创建任务成功，请耐心等待，不要退出界面')
    taskId.value = res.data.data.output.taskId
    // 轮询任务状态
    startPolling();
  } else {
    message.error('创建任务失败' + res.data.message)
  }
}

let pollingTimer: NodeJS.Timeout = null;
// 开始轮询
const startPolling = () => {
  if (!taskId.value) {
    return
  }
  pollingTimer = setInterval(async () => {
    try {
      const res = await getPictureOutPaintingTaskUsingGet({
        taskId: taskId.value,
      })
      if (res.data.code === 0 && res.data.data) {
        const taskResult = res.data.data.output
        if (taskResult.taskStatus === 'SUCCEEDED') {
          console.log(taskResult)
          message.success('扩图任务成功')
          resultImageUrl.value = taskResult.outputImageUrl
          clearPolling()
        } else if (taskResult.taskStatus === 'FAILED') {
          console.log(taskResult.taskStatus === 'FAILED')
          message.error('扩图任务失败' + taskResult.message)
          clearPolling()
        }
      }
    } catch (error) {
      console.error('轮询任务状态失败', error)
      message.error('检测任务状态失败，请稍后重试')
      clearPolling()
    }
  }, 3000)
}
// 清理轮询
const clearPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value = null
  }
}

// 清理定时器，避免内存泄漏
// onUnmounted(() => {
//   clearPolling()
// })
</script>
<style>
.image-out-painting {
  text-align: center;
}
</style>
